import pygame
import pygame.freetype
import logging
import os
from typing import Tuple, Optional

class Theme:
    def __init__(self):
        # 现代化青少年喜欢的颜色方案
        
        # 主题色：明亮的蓝紫渐变
        self.primary_color = (94, 114, 228)  # 明亮的蓝紫色
        self.secondary_color = (130, 94, 228)  # 紫色变种
        self.accent_color = (255, 86, 155)  # 亮粉色强调色
        
        # 基础颜色
        self.background_color = (248, 249, 254)  # 接近白色的背景
        self.text_color = (50, 60, 93)  # 柔和的深蓝色文字
        self.input_color = (94, 114, 228)  # 使用主题色作为输入文字
        
        # 卡片背景
        self.card_bg_color = (255, 255, 255)  # 纯白色卡片
        self.card_shadow = (0, 0, 0, 15)  # 透明阴影
        
        # 状态颜色
        self.correct_color = (66, 214, 164)  # 青绿色
        self.wrong_color = (255, 92, 108)    # 明亮的红色
        self.highlight_color = (94, 114, 228)  # 高亮使用主题色
        
        # 界面元素颜色
        self.button_color = (94, 114, 228)  # 使用主题色
        self.button_hover_color = (130, 94, 228)  # 悬停时使用次要主题色
        self.button_text_color = (255, 255, 255)  # 按钮文字为白色
        self.progress_bar_color = (66, 214, 164)  # 使用绿色
        self.progress_bar_bg = (233, 236, 239)  # 进度条背景色
        
        # 字体设置
        self.font_family = None  # 使用默认字体
        self.title_size = 48
        self.text_size = 24
        self.small_text_size = 18
        
        # 边框颜色和圆角
        self.border_color = (233, 236, 239)  # 浅灰色边框
        self.border_radius = 12  # 边框圆角
        
        # 动画效果配置
        self.animation_speed = 0.2  # 动画速度（秒）
        
        # 字体初始化
        pygame.freetype.init()
        
        # 尝试加载中文字体
        chinese_fonts = [
            "Microsoft YaHei",
            "SimHei",
            "NSimSun",
            "STHeiti",
            "WenQuanYi Micro Hei"
        ]
        
        self.font = None
        for font_name in chinese_fonts:
            try:
                self.font = pygame.freetype.SysFont(font_name, self.text_size)
                if self.font.get_metrics("测试")[0]:  # 测试是否支持中文
                    break
            except:
                continue
                
        if self.font is None:
            self.font = pygame.freetype.SysFont(None, self.text_size)  # 使用默认字体
            logging.warning("未能加载中文字体，将使用默认字体")
            
        # 尝试加载自带字体
        font_path = os.path.join("assets", "fonts", "SourceHanSansCN-Normal.otf")
        if os.path.exists(font_path):
            try:
                self.font = pygame.freetype.Font(font_path, self.text_size)
            except:
                logging.error(f"加载自带字体失败: {font_path}")
                self.font = pygame.freetype.SysFont(None, self.text_size)
            
        # 尝试加载支持表情符号的字体
        emoji_fonts = [
            "Segoe UI Emoji",  # Windows
            "Apple Color Emoji",  # macOS
            "Noto Color Emoji",  # Linux
            "Noto Emoji",
            "Symbola"
        ]
        
        # 先尝试加载表情符号字体
        self.emoji_font = None
        for font_name in emoji_fonts:
            try:
                self.emoji_font = pygame.freetype.SysFont(font_name, self.text_size)
                if self.emoji_font.get_metrics("✅")[0]:  # 测试是否支持表情符号
                    break
            except:
                continue

    def draw_text(self, surface, text, pos, color=None, size=24, center=False, shadow=False):
        """绘制文本，支持阴影效果"""
        if color is None:
            color = self.text_color
            
        # 设置字体大小
        self.font.size = size
        if self.emoji_font:
            self.emoji_font.size = size
        
        # 选择合适的字体渲染
        if text in ["✅", "❌"] and self.emoji_font:
            text_surface, rect = self.emoji_font.render(text, color)
        else:
            text_surface, rect = self.font.render(text, color)
        
        if center:
            # 居中对齐
            pos = (pos[0] - rect.width // 2, pos[1] - rect.height // 2)
            
        # 绘制阴影效果（如果需要）
        if shadow:
            shadow_surface, _ = self.font.render(text, (70, 70, 70, 100))
            shadow_pos = (pos[0] + 2, pos[1] + 2)  # 阴影偏移
            surface.blit(shadow_surface, shadow_pos)
            
        # 绘制文本
        surface.blit(text_surface, pos)

    def render_text(self, text: str, size: int = None, color = None) -> pygame.Surface:
        """渲染文本"""
        if size is not None:
            self.font.size = size
            if self.emoji_font:
                self.emoji_font.size = size
        if color is None:
            color = self.text_color
            
        try:
            # 检查是否是表情符号
            if text in ["✅", "❌"] and self.emoji_font:
                surface, rect = self.emoji_font.render(text, color)
            else:
                surface, rect = self.font.render(text, color)
            return surface
        except:
            logging.error(f"渲染文本失败: {text}")
            return pygame.Surface((1, 1))  # 返回空表面 

    def get_text_width(self, text: str, size: int = 32) -> int:
        """获取文本宽度
        
        Args:
            text: 要测量的文本
            size: 字体大小
            
        Returns:
            int: 文本宽度（像素）
        """
        # 保存当前字体大小
        current_size = self.font.size
        
        # 设置临时字体大小
        self.font.size = size
        
        # 获取文本尺寸
        _, rect = self.font.render(text, self.text_color)
        width = rect.width
        
        # 恢复原来的字体大小
        self.font.size = current_size
        
        return width
        
    def draw_rounded_rect(self, surface: pygame.Surface, rect: pygame.Rect, 
                          color: Tuple, radius: Optional[int] = None, 
                          border: int = 0, border_color: Optional[Tuple] = None):
        """绘制圆角矩形
        
        Args:
            surface: 目标表面
            rect: 矩形区域
            color: 填充颜色
            radius: 圆角半径
            border: 边框宽度
            border_color: 边框颜色
        """
        if radius is None:
            radius = self.border_radius
            
        if border_color is None:
            border_color = self.border_color
            
        # 绘制圆角矩形
        rect_surface = pygame.Surface((rect.width, rect.height), pygame.SRCALPHA)
        
        # 填充矩形
        pygame.draw.rect(rect_surface, color, (0, 0, rect.width, rect.height), 
                        border_radius=radius)
        
        # 如果需要边框
        if border > 0:
            pygame.draw.rect(rect_surface, border_color, 
                            (0, 0, rect.width, rect.height), 
                            width=border, border_radius=radius)
        
        # 绘制到目标表面
        surface.blit(rect_surface, rect)
        
    def draw_card(self, surface: pygame.Surface, rect: pygame.Rect, 
                 with_shadow: bool = True, border: int = 0):
        """绘制卡片（带阴影效果）
        
        Args:
            surface: 目标表面
            rect: 卡片区域
            with_shadow: 是否绘制阴影
            border: 边框宽度
        """
        # 如果需要阴影
        if with_shadow:
            # 创建阴影表面
            shadow_rect = pygame.Rect(rect.x + 4, rect.y + 4, rect.width, rect.height)
            self.draw_rounded_rect(surface, shadow_rect, self.card_shadow, border=0)
            
        # 绘制卡片主体
        self.draw_rounded_rect(surface, rect, self.card_bg_color, 
                             border=border, border_color=self.border_color)
        
    def draw_button(self, surface: pygame.Surface, rect: pygame.Rect, 
                   text: str, is_hover: bool = False, is_active: bool = False):
        """绘制按钮
        
        Args:
            surface: 目标表面
            rect: 按钮区域
            text: 按钮文本
            is_hover: 是否悬停
            is_active: 是否激活
        """
        # 选择按钮颜色
        if is_active:
            color = self.accent_color
        elif is_hover:
            color = self.button_hover_color
        else:
            color = self.button_color
            
        # 绘制按钮背景
        self.draw_rounded_rect(surface, rect, color)
        
        # 绘制按钮文本
        self.draw_text(surface, text, 
                     (rect.centerx, rect.centery), 
                     color=self.button_text_color, 
                     center=True)
                     
    def draw_progress_bar(self, surface: pygame.Surface, rect: pygame.Rect, 
                         progress: float, text: Optional[str] = None):
        """绘制进度条
        
        Args:
            surface: 目标表面
            rect: 进度条区域
            progress: 进度值（0-1之间）
            text: 显示的文本
        """
        # 绘制背景
        self.draw_rounded_rect(surface, rect, self.progress_bar_bg)
        
        # 绘制进度
        if progress > 0:
            progress_width = int(rect.width * max(0, min(1, progress)))
            progress_rect = pygame.Rect(rect.x, rect.y, progress_width, rect.height)
            self.draw_rounded_rect(surface, progress_rect, self.progress_bar_color)
            
        # 绘制文本
        if text:
            self.draw_text(surface, text, 
                         (rect.centerx, rect.centery), 
                         color=self.text_color, 
                         center=True) 